#!/usr/bin/perl

use strict;
use Net::Netrc;

use WWW::NikePlus;
use Toolkit;

my $directory = "$ENV{'HOME'}/.nike";

mkdir($directory) unless( -d $directory );

dbmopen(my %map, "$directory/challenges", 0666);
my $mach = Net::Netrc->lookup('nikeplus');

my $np = WWW::NikePlus->new(
  login    => $mach->login(),
  password => $mach->password()
);

my @challenges = $np->get_challenge_list(active => 1);

my @table = (['name', 'team', 'rank', 'previous', 'delta']);
foreach my $chal (@challenges) {
  $chal->getDetail();
  $chal->getMembers();

  my $prev = $map{$chal->getID()} || 0;
  my $rank = $chal->getRank();
  my $team = '';

  if($chal->isTeam()) {
    $rank = $chal->getTeamRank();
    $team = $chal->getTeam()->{'name'};
  }
  $map{$chal->getID()} = $rank;

  my $name = $chal->getName();
  if( length($name) > 33 ){
    $name = substr($name, 0, 30);
    $name .= '...';
  }

  if( length($team) > 13 ){
    $team = substr($team, 0, 10);
    $team .= '...';
  }

  push(@table, [$name, $team, $rank, $prev, ($rank - $prev) * -1]);
}

dump_table(table => \@table, 'sort' => 0);
